import { order, comment } from '../models'
import { sequelize } from '../models/'
import moment from 'moment'
import uuid from 'node-uuid'
import { Router } from 'express'
let getCodeByCount = function (count, length = 4) {
  let result = count + ''
  for (let i = 0; i <= length - result.length; i++) {
    result = '0' + result
  }
  return result
}
let routes = Router()

routes.get('/', (req, res) => {
  let sql = 'select o.*, u.username as publisher from orders as o left join users as u on o.user_id = u.id where o.recipient_id is null'
  sequelize.query(sql, {
    type: sequelize.QueryTypes.SELECT
  }).then(orders => {
    res.json(orders)
  })
})

routes.post('/recipient', (req, res) => {
  sequelize.query('update orders set recipient_id =? where id = ?', {
    replacements: [req.body.recipient_id, req.body.id]
  }).then(() => {
    res.json({
      message: 'recipient success'
    })
  })
})
routes.post('/status', (req, res) => {
  sequelize.query('update orders set status =? where id = ?', {
    replacements: [req.body.status, req.body.id]
  }).then(() => {
    res.json({
      message: 'update success'
    })
  })
})
routes.post('/', (req, res) => {
  let orderInfo = Object.assign({
    id: ''
  }, req.body)
  if (!orderInfo.id || orderInfo.id === '') {
    orderInfo.id = uuid.v4()
  }
  order.count().then(count => {
    let code = moment().format('YYYYMMDD') + getCodeByCount(count, 5)
    if (!orderInfo.code || orderInfo.code === '') {
      orderInfo.code = code
    }
    orderInfo.deadline = new Date(orderInfo.deadline)
    return order.upsert(orderInfo)
  }).then(() => {
    res.json({
      id: orderInfo.id
    })
  })
})

routes.get('/:id', (req, res) => {
  order.findAll({
    raw: true,
    where: {
      id: req.params.id
    }
  }).then(orders => {
    res.json(orders)
  })
})

routes.get('/recipient/:id', (req, res) => {
  order.findAll({
    raw: true,
    where: {
      recipient_id: req.params.id
    }
  }).then(orders => {
    res.json(orders)
  })
})
routes.get('/user/:id', (req, res) => {
  let sql = 'select o.*, u.username as publisher, r.username as recipient from orders as o left join users as u on o.user_id = u.id left join users as r on o.recipient_id = r.id  where o.user_id = ?';
  sequelize.query(sql, {
    type: sequelize.QueryTypes.SELECT,
    replacements: [req.params.id]
  }).then(orders => {
    res.json(orders)
  })

})

routes.post('/comments', (req, res) => {
  let commentInfo = Object.assign({
    id: uuid.v4()
  }, req.body)
  comment.upsert(commentInfo).then(() => res.json({}))
})

routes.get('/comments/:id', (req, res) => {
  comment.findAll({
    raw: true,
    where: {
      order_id: req.params.id
    }
  }).then(comments => res.json(comments))
})

export default routes
